<script setup>

import {getCurrentInstance, nextTick, onMounted, ref} from "vue";
import {getAiJudgeAndRecommendByVideo, getVideoDetail} from "../../../../api/user/user.js";
import hljs from "highlight.js";
import {fetchEventSource} from "@microsoft/fetch-event-source";
import {ElMessage} from "element-plus";
import {onBeforeRouteLeave, onBeforeRouteUpdate} from "vue-router";
import {clearChatHistory} from "@/api/ai/studentChatAIApi.js";

let loading = ref(false);
let echartsDom = null;
// 通过 internalInstance.appContext.config.globalProperties 获取全局属性或方法
let internalInstance = getCurrentInstance();
const controller = new AbortController();
const signal = controller.signal;
let echarts = internalInstance.appContext.config.globalProperties.$echarts;
// 根据视频情况评测提示词
let videoEvaluateTip = ref();
// 根据视频情况评测
let videoEvaluate = ref('');
// 滚动条实例
const scrollbarRef = ref();
// 计数器内部实例
const innerRef = ref();
function dealAnswer(data,answer) {
  let sseData = data;
  sseData = sseData.replaceAll("&#32;", " ").replaceAll("&#92n", "\n")
  answer += sseData;
  return answer;
}
async function setScrollToBottom() {
  // 注意：需要通过 nextTick 以等待 DOM 更新完成
  await nextTick()
  const max = innerRef.value.clientHeight
  scrollbarRef.value.setScrollTop(max)
}
onBeforeRouteLeave((to, from, next) => {
  controller.abort()
  next()
})
onBeforeRouteUpdate((to, from, next) => {
  controller.abort()
  next()
})

// 将md转化为html
function mdToHtml(content,callback) {
  import('markdown-it').then(module => {
    const md = module.default('commonmark', {
      highlight: function (str, lang) {
        if (lang && hljs.getLanguage(lang)) {
          try {
            return '<pre class="hljs"><code>' +
                hljs.highlight(lang, str, true).value +
                '</code></pre>';
          } catch (__) {}
        }

        return '<pre class="hljs"><code>' + md.utils.escapeHtml(str) + '</code></pre>';
      }
    });
    callback(md.render(content));
  });
}
// 用户进入页面时 需要清空和ai对话的历史记录
clearChatHistory();
getAiJudgeAndRecommendByVideo().then(res =>
    {
      videoEvaluateTip.value = res.data;
      let answer = '';
      let nowHtml = '';
      setInterval(async () => {
        if ( nowHtml.length > videoEvaluate.value.length ) {
          let nowLen = videoEvaluate.value.length;
          if ( nowHtml[nowLen] === '<' ) {
            while ( nowHtml[nowLen] !== '>' ) {
              nowLen ++;
            }
          }
          videoEvaluate.value = nowHtml.slice(0,nowLen+1);
          await setScrollToBottom();
        }
      },70)
      fetchEventSource("/api/aiChat/chat?question="+videoEvaluateTip.value,{
        method: 'GET',
        headers: {
          'content-type': 'application/json',
          'token': localStorage.getItem("token")
        },
        signal: signal,
        openWhenHidden: true,
        onmessage(event) {
          answer = dealAnswer(event.data,answer)
          if ( event.data === '&#92n[DONE]') {
            // 发送完成结束对话
            controller.abort();
            return;
          }
          mdToHtml(answer,(html)=>{
            nowHtml = html;
          })
        },
        onclose(event) {
          controller.abort();
        },
        onerror(event) {
          ElMessage.error("对话失败，请重试");
          controller.abort();
        }
      });
      loading.value = false;
    }
)
onMounted(async () => {
  await nextTick(() => {
    echartsDom = document.querySelector('.echarts');
    getVideoDetail().then(res => {
      let dataArray = [];
      for (let i = 0; i < res.data.length; i++) {
        dataArray.push({value: res.data[i].frequency, name: res.data[i].tagName})
      }
      console.log(dataArray)
      const myEcharts = echarts.init(echartsDom);
      const option = {
        tooltip: {
          trigger: 'item'
        },
        legend: {
          top: '5%',
          left: 'center'
        },
        grid: {
          left: '50%',
          right: '50%',
          bottom: '50%',
          containLabel: true
        },
        series: [
          {
            name: 'Access From',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center',
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 40,
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: dataArray
          }
        ]
      };
      myEcharts.setOption(option)
    })
  })
})
</script>

<template>
  <div class="common-area">
    <el-container class="container-area">
      <div class="box">
        <div class="echarts"></div>
        <el-divider direction="vertical" class="divider"></el-divider>
      </div>
      <div
          v-loading="loading"
          element-loading-text="Loading..."
          class="ai-recommend">
        <div class="ai-title">📚AI总结及推荐结果如下：</div>
        <div v-html="videoEvaluate" style="font-size: 15px"></div>
      </div>
    </el-container>
  </div>
</template>

<style lang="less" scoped>
.common-area {
  width: 100%;
  height: 700px;

  .container-area {
    width: 100%;
    height: 100%;
    display: flex;

    .box {
      width: 70%;
      height: 100%;
      display: flex;

      .echarts {
        width: 100%;
        height: 100%;
      }

      .divider {
        margin-right: 10px;
        height: 100%;
      }
    }

    .ai-recommend {
      flex: 1;

      .ai-title {
        font-weight: bold;
        margin-top: 13px;
        width: 100%
      }
    }
  }
}
</style>